/* programme calculant fibo(x) avec la bibli thread*/

#include "thread.h" 
#include <stdio.h>
#include <stdlib.h>
#include <time.h>


static void* fibonacci(void* i)
{
   int *value =i;
   int *value_1=malloc(sizeof( int));
   int *value_2=malloc(sizeof(int));

  if((*value)<=1){
    int* ret=malloc(sizeof(int));
    *ret=1;
    thread_exit(ret);
  }
  else
    {
       int  *result=malloc(sizeof( int));
      thread_t thread1,thread2;
      *value_1=*value-1;
      *value_2=*value-2;  
      thread_create(&thread1,fibonacci,(void*)value_1);
      thread_create(&thread2,fibonacci,(void*)value_2);
      thread_join(&thread1,(void**)&value_1);
      thread_join(&thread2,(void**)&value_2); 
      *result= (*value_1)+(*value_2);
      free(value_1);
      free(value_2);

      //fprintf(stderr,"--------> %d\n",*result);
      thread_exit(result);
    }
}


int main(int argv, char** argc)
{
  
  if(argv!=2){
    printf("mettre un entier positif en argument\n");
    return 0;
  }
  
  int *value=malloc(sizeof(int));
  *value=atoi(argc[1]);
  if(*value>30)
    {
      printf("votre valeur est trop importante\n mettre un entier <10 pour ne pas créer trop de thread\n");
      return EXIT_FAILURE;
    }
  if(*value<=1)
    {
      //printf(" fibo(%d)= 1\n",*value);
      return EXIT_SUCCESS;
    }

  double debut, fin;
  debut=clock();
  thread_t thread;
  int *result;
  *value=*value-1;
  thread_create(&thread, fibonacci,(void*)value);
  thread_join(&thread,(void*)&result);
  printf("le resultat : fibo(%d)=%d\n",(*value+1),*result);
  free(value);
  free(result);

  fin=clock();
  fprintf(stderr,"temps d'exécution : %f s\n",(double) (fin-debut)/(double)CLOCKS_PER_SEC);

  return EXIT_SUCCESS;
}
